<script setup lang="ts">
import { ref, watch } from 'vue'
import { useDraggable } from '@vueuse/core'

const barHeight = () => window.outerHeight - window.innerHeight

const screenToClient = (x: number, y: number) => {
  return {
    left: x - window.screenX,
    top: y - window.screenY - barHeight()
  }
}

const clientToScreen = (left: number, top: number) => {
  return {
    x: left + window.screenX,
    y: top + window.screenY + barHeight()
  }
}

const el = ref<HTMLElement | null>(null)
const { x, y } = useDraggable(el, {
  initialValue: { x: 40, y: 40 }
})
let left = ref(40)
let top = ref(40)

let channel = new BroadcastChannel('poker')
watch([x, y], ([x, y]) => {
  channel.postMessage(clientToScreen(x, y))
  left.value = x
  top.value = y
})

function onmessage(x: number, y: number) {
  let client = screenToClient(x, y)
  left.value = client.left
  top.value = client.top
}
onmessage(500, 300)
channel.onmessage = (e) => {
  onmessage(e.data.x, e.data.y)
}
</script>
<template>
  <div
    class="poker"
    ref="el"
    :style="{
      left: left + 'px',
      top: top + 'px'
    }"
    style="position: fixed"
  ></div>
</template>

<style scoped>
.poker {
  width: 127px;
  height: 178px;
  background-image: url(./poker.jpg);
  background-size: 100% 100%;
  cursor: grab;
}
</style>
: number: number
